package com.langsheng.lsintell.network;

import com.langsheng.lsintell.cmd.request.LSRequest;
import com.langsheng.lsintell.cmd.response.LSResponse;
import com.langsheng.lsintell.data.LSServerInfo;
import com.langsheng.lsintell.interfaces.LSResponseListener;
import com.langsheng.lsintell.utils.LSThreadPool;

/**
 * Created by xxw on 2017/2/27.
 */
class LSNetwork {

    private final static String ip = "101.37.78.72";
    private final static int port = 8010;
    private static LSNetwork ourInstance = new LSNetwork();
    private LSSocketClientEx socket;

    public static LSNetwork getInstance() {
        return ourInstance;
    }

    private LSNetwork() {
    }

    public synchronized void sendRequest(LSRequest req, LSResponseListener listener) {
        LSThreadPool.getInstance().addCachedThread(new network(req, listener));
    }

    private class network implements Runnable {

        private LSRequest request;
        private LSResponseListener listener;

        public network(LSRequest req, LSResponseListener listener) {
            this.request = req;
            this.listener = listener;
        }

        @Override
        public void run() {
            boolean isConnected = connectServer();
            try {
                if (isConnected) {
                    LSResponse response = socket.getSingleResponse(request);
                    listener.onResponse(response);
                } else {
                    listener.onResponse(null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                listener.onResponse(null);
                socket.close();
                socket = null;
            }
        }
    }

    private boolean connectServer() {
        if (socket == null) {
            socket = new LSSocketClientEx();
        }

        int connectCount = 0;
        while (!socket.isConnected() && connectCount < 3) {
            socket.connect(new LSServerInfo(ip, port));
            connectCount++;
        }
        return socket.isConnected();
    }
}
